<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use App\Admin\Article;

class ArticleController extends Controller
{
    // 显示文章列表
    public function index () {
        $data = Article::all();
        return view('admin.article.index', compact('data'));
    }

    // 添加文章
    public function add (Request $request) {
        // 如果是get请求，显示添加文章视图
        if($request->isMethod('get')) {
            return view('admin.article.add');
        } else {
            $data = $request->except('_token', 'file');
            $data['admin_name'] = $request->user()->username;
            
            $data['content'] = $data['editorValue'];
            $data['article_time'] = date('Y-m-d H:i:s');

            unset($data['editorValue']);

            $res = Article::insert($data);
            
            echo $res ? '1' : '0';
        }
    }

    // 下架文章
    public function changeStatus ($id) {
        $status = Article::where('id', $id)->value('status');
        
        if($status == '1') {
            $status = '2';
        } else {
            $status = '1';
        }
        
        $res = Article::where('id', $id)->update(['status'=>$status]);
        
        echo $res ? '1' : '0';
    }

    // 修改文章
    public function edit ($id, Request $request) {
        if($request->isMethod("get")) {
            $data = Article::find($id);
            return view('admin.article.edit', compact('data'));
        } else {
            $data = $request->except('_token', 'file');

            $data['content'] = $data['editorValue'];
            $data['article_time'] = date('Y-m-d H:i:s');

            unset($data['editorValue']);

            $res = Article::where('id', $id)->update($data);
            
            echo $res ? '1' : '0';
        }
        
    }

    // 删除文章
    public function delete ($id) {
        $res = Article::where('id', $id)->delete();

        echo $res ? '1' : '0';
    }
}
